<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/roee/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/roee/lib/pace/pace-theme-flash.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/roee/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/roee/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/roee/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="ios开发," />








  <link rel="shortcut icon" type="image/x-icon" href="/roee/favicon.ico?v=5.1.2" />






<meta name="description" content="如果在网速一定的情境下，大文件（目前指的是100M以上的文件）的下载对用户来说是一段不短的时间，用户体验不是很好。">
<meta name="keywords" content="ios开发">
<meta property="og:type" content="article">
<meta property="og:title" content="使用NSURLSession实现iOS大文件分块下载">
<meta property="og:url" content="http://rjll.gitee.io/roee/2017/07/08/使用NSURLSession实现iOS大文件分块下载/index.html">
<meta property="og:site_name" content="Roee&#39;s Blog">
<meta property="og:description" content="如果在网速一定的情境下，大文件（目前指的是100M以上的文件）的下载对用户来说是一段不短的时间，用户体验不是很好。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-05-19T16:17:34.560Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="使用NSURLSession实现iOS大文件分块下载">
<meta name="twitter:description" content="如果在网速一定的情境下，大文件（目前指的是100M以上的文件）的下载对用户来说是一段不短的时间，用户体验不是很好。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/roee/',
    scheme: 'Gemini',
    sidebar: {"position":"left","display":"always","offset":12,"offset_float":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://rjll.gitee.io/roee/2017/07/08/使用NSURLSession实现iOS大文件分块下载/"/>





  <title>使用NSURLSession实现iOS大文件分块下载 | Roee's Blog</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/roee/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Roee's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/roee/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/roee/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-romantic">
          <a href="/roee/520/romanticPage.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heart"></i> <br />
            
            R❤️W
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/roee/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/roee/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://rjll.gitee.io/roee/roee/2017/07/08/使用NSURLSession实现iOS大文件分块下载/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Roee">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/roee/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Roee's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">使用NSURLSession实现iOS大文件分块下载</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-07-08T16:00:20+08:00">
                2017-07-08
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/roee/2017/07/08/使用NSURLSession实现iOS大文件分块下载/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2017/07/08/使用NSURLSession实现iOS大文件分块下载/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>如果在网速一定的情境下，大文件（目前指的是100M以上的文件）的下载对用户来说是一段不短的时间，用户体验不是很好。<br><a id="more"></a><br>分块下载文件实现原理<br>如果要实现文件的分段下载，我们首先需要知道要下载的文件的大小，这里需要向服务器发送HTTP请求，请求方法为HEAD，这样服务器只会给客户端返回response的包头信息，不会发送数据信息，然后我们通过包头信息中的Content-Length字段可以得到要下载的文件的总长度。</p>
<figure class="highlight obj-c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="keyword">void</span>)getFileTotalLengthWithURL:(<span class="built_in">NSString</span> *)url</span><br><span class="line">                       completion:(<span class="keyword">void</span>(^)(<span class="built_in">NSInteger</span> length))completion&#123;</span><br><span class="line">    <span class="built_in">NSURL</span> *URL = [<span class="built_in">NSURL</span> URLWithString:url];</span><br><span class="line">    <span class="built_in">NSMutableURLRequest</span> *request = [<span class="built_in">NSMutableURLRequest</span> requestWithURL:URL];</span><br><span class="line">    request.HTTPMethod = <span class="string">@"HEAD"</span>;</span><br><span class="line">    <span class="built_in">NSURLSession</span> *session = [<span class="built_in">NSURLSession</span> sharedSession];</span><br><span class="line">    <span class="built_in">NSURLSessionDataTask</span> *dataTask = [session dataTaskWithRequest:request completionHandler:^(<span class="built_in">NSData</span> * _Nullable data, <span class="built_in">NSURLResponse</span> * _Nullable response, <span class="built_in">NSError</span> * _Nullable error) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> ([response isKindOfClass:[<span class="built_in">NSHTTPURLResponse</span> <span class="keyword">class</span>]]) &#123;</span><br><span class="line">            <span class="built_in">NSHTTPURLResponse</span> *tmpResponse = (<span class="built_in">NSHTTPURLResponse</span> *)response;</span><br><span class="line">            <span class="built_in">NSLog</span>(<span class="string">@"allHeaderFields:%@"</span>, tmpResponse.allHeaderFields);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">NSInteger</span> fileTotalLength = response.expectedContentLength;</span><br><span class="line">        completion(fileTotalLength);</span><br><span class="line">    &#125;];</span><br><span class="line">    [dataTask resume];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>获取到要下载的文件的总长度之后，在本地沙盒中创建一个同样大小的文件</p>
<figure class="highlight obj-c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="keyword">void</span>)multiDownloadWithFileLength:(<span class="built_in">NSInteger</span>)fileLength url:(<span class="built_in">NSURL</span> *)url&#123;</span><br><span class="line">    _wholeFileLength = fileLength;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">NSString</span> *filePath = [<span class="keyword">self</span> filePathWithFileName:url.lastPathComponent];</span><br><span class="line">    <span class="built_in">NSFileManager</span> *fm = [<span class="built_in">NSFileManager</span> defaultManager];</span><br><span class="line">    <span class="keyword">if</span> ([fm fileExistsAtPath:filePath]) &#123;</span><br><span class="line">        [fm removeItemAtPath:filePath error:<span class="literal">nil</span>];</span><br><span class="line">    &#125;</span><br><span class="line">    [[<span class="built_in">NSFileManager</span> defaultManager] createFileAtPath:filePath contents:<span class="literal">nil</span> attributes:<span class="literal">nil</span>];</span><br><span class="line"></span><br><span class="line">    _filePath = filePath;</span><br><span class="line">    _fileHandle = [<span class="built_in">NSFileHandle</span> fileHandleForWritingAtPath:filePath];</span><br><span class="line">    [_fileHandle truncateFileAtOffset:fileLength];</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">while</span> (_completedLength &lt; fileLength) &#123;</span><br><span class="line">        <span class="keyword">long</span> <span class="keyword">long</span> startSize = _completedLength;</span><br><span class="line">        <span class="keyword">long</span> <span class="keyword">long</span> endSize = startSize+blockSize;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> (endSize &gt; fileLength) &#123;</span><br><span class="line">            endSize = fileLength - <span class="number">1</span>;</span><br><span class="line">            _completedLength = fileLength;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            _completedLength += blockSize;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//一个operation对应一个downloadTask</span></span><br><span class="line">        </span><br><span class="line">        <span class="built_in">NSBlockOperation</span> *operation = [<span class="built_in">NSBlockOperation</span> blockOperationWithBlock:^&#123;</span><br><span class="line">            </span><br><span class="line">            <span class="built_in">NSString</span> *range=[<span class="built_in">NSString</span> stringWithFormat:<span class="string">@"bytes=%lld-%lld"</span>, startSize, endSize];</span><br><span class="line">            <span class="built_in">NSMutableURLRequest</span> *request = [<span class="built_in">NSMutableURLRequest</span> requestWithURL:url];</span><br><span class="line">            [request setValue:range forHTTPHeaderField:<span class="string">@"Range"</span>];</span><br><span class="line">            <span class="built_in">NSLog</span>(<span class="string">@"requestHeader:%@"</span>, request.allHTTPHeaderFields);</span><br><span class="line">            <span class="built_in">NSURLSessionDownloadTask</span> *task = [<span class="keyword">self</span>.session downloadTaskWithRequest:request];</span><br><span class="line">            </span><br><span class="line">            [task resume];       </span><br><span class="line">        &#125;];</span><br><span class="line">        [_queue addOperation:operation];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>每个请求块的大小</p>
<figure class="highlight obj-c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#define blockSize 1024*1024</span></span><br></pre></td></tr></table></figure>
<p>新建一个下载队列，循环发送请求，在请求头中设置Range字段</p>
<figure class="highlight obj-c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSOperationQueue</span> *queue = [<span class="built_in">NSOperationQueue</span> currentQueue];</span><br><span class="line">    <span class="built_in">NSBlockOperation</span> *addOperationOP = [<span class="built_in">NSBlockOperation</span> blockOperationWithBlock:^&#123;</span><br><span class="line">        <span class="keyword">while</span> (_completedLength &lt; fileLength) &#123;</span><br><span class="line">            <span class="keyword">long</span> <span class="keyword">long</span> startSize = _completedLength;</span><br><span class="line">            <span class="keyword">long</span> <span class="keyword">long</span> endSize = startSize+blockSize;</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">if</span> (endSize &gt; fileLength) &#123;</span><br><span class="line">                endSize = fileLength - <span class="number">1</span>;</span><br><span class="line">                _completedLength = fileLength;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                _completedLength += blockSize;</span><br><span class="line">            &#125;</span><br><span class="line">            </span><br><span class="line">            <span class="comment">//一个operation对应一个downloadTask</span></span><br><span class="line">            </span><br><span class="line">            <span class="built_in">NSBlockOperation</span> *operation = [<span class="built_in">NSBlockOperation</span> blockOperationWithBlock:^&#123;</span><br><span class="line">                </span><br><span class="line">                <span class="built_in">NSString</span> *range=[<span class="built_in">NSString</span> stringWithFormat:<span class="string">@"bytes=%lld-%lld"</span>, startSize, endSize];</span><br><span class="line">                <span class="built_in">NSMutableURLRequest</span> *request = [<span class="built_in">NSMutableURLRequest</span> requestWithURL:url];</span><br><span class="line">                [request setValue:range forHTTPHeaderField:<span class="string">@"Range"</span>];</span><br><span class="line">                <span class="built_in">NSLog</span>(<span class="string">@"requestHeader:%@"</span>, request.allHTTPHeaderFields);</span><br><span class="line">                <span class="built_in">NSURLSessionDownloadTask</span> *task = [<span class="keyword">self</span>.session downloadTaskWithRequest:request];</span><br><span class="line">                </span><br><span class="line">                [task resume];</span><br><span class="line">                </span><br><span class="line">            &#125;];</span><br><span class="line">            [queue addOperation:operation];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;];</span><br><span class="line">    [queue addOperation:addOperationOP];</span><br></pre></td></tr></table></figure>
<p>在代理方法中将获取到的数据写到已经创建好的空文件的对应的位置中</p>
<figure class="highlight obj-c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"> - (<span class="keyword">void</span>)URLSession:(<span class="built_in">NSURLSession</span> *)session downloadTask:(<span class="built_in">NSURLSessionDownloadTask</span> *)downloadTask didFinishDownloadingToURL:(<span class="built_in">NSURL</span> *)location&#123;</span><br><span class="line">    </span><br><span class="line">    DLQData *tmpReceivedData = [[DLQData alloc] init];</span><br><span class="line">    <span class="built_in">NSInteger</span> startSize = <span class="number">0</span>;</span><br><span class="line">    <span class="built_in">NSInteger</span> endSize = <span class="number">0</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> ([downloadTask.response isKindOfClass:[<span class="built_in">NSHTTPURLResponse</span> <span class="keyword">class</span>]]) &#123;</span><br><span class="line">        <span class="built_in">NSHTTPURLResponse</span> *tmpResponse = (<span class="built_in">NSHTTPURLResponse</span> *)downloadTask.response;</span><br><span class="line">        <span class="built_in">NSDictionary</span> *dic = tmpResponse.allHeaderFields;</span><br><span class="line">        <span class="built_in">NSLog</span>(<span class="string">@"diiiiiic: %@"</span>, dic[<span class="string">@"Content-Range"</span>]);</span><br><span class="line">        <span class="built_in">NSString</span> *fileRange = dic[<span class="string">@"Content-Range"</span>];</span><br><span class="line">        fileRange = [fileRange stringByReplacingOccurrencesOfString:<span class="string">@"bytes"</span> withString:<span class="string">@""</span>];</span><br><span class="line">        fileRange = [fileRange stringByReplacingOccurrencesOfString:<span class="string">@" "</span> withString:<span class="string">@""</span>];</span><br><span class="line">        <span class="built_in">NSArray</span> *aTmp1 = [fileRange componentsSeparatedByString:<span class="string">@"/"</span>];</span><br><span class="line">        <span class="built_in">NSArray</span> *aTmp2 = @[];</span><br><span class="line">        <span class="keyword">if</span> (aTmp1.count) &#123;</span><br><span class="line">            <span class="built_in">NSString</span> *tmpStr = aTmp1[<span class="number">0</span>];</span><br><span class="line">            aTmp2 = [tmpStr componentsSeparatedByString:<span class="string">@"-"</span>];</span><br><span class="line">            <span class="keyword">if</span> (aTmp1.count &gt;= <span class="number">2</span>) &#123;</span><br><span class="line">                <span class="built_in">NSString</span> *startSizeStr = aTmp2[<span class="number">0</span>];</span><br><span class="line">                <span class="built_in">NSString</span> *endSizeStr = aTmp2[<span class="number">1</span>];</span><br><span class="line">                startSize = startSizeStr.integerValue;</span><br><span class="line">                endSize = endSizeStr.integerValue;</span><br><span class="line">        </span><br><span class="line">                tmpReceivedData.data = [<span class="built_in">NSData</span> dataWithContentsOfURL:location];</span><br><span class="line">                tmpReceivedData.startSize = startSize;</span><br><span class="line">                tmpReceivedData.endSize = endSize;</span><br><span class="line">                </span><br><span class="line">                [_fileHandle seekToFileOffset:tmpReceivedData.startSize];</span><br><span class="line">                [_fileHandle writeData:tmpReceivedData.data];</span><br><span class="line">                [_fileData appendData:tmpReceivedData.data];</span><br><span class="line">                </span><br><span class="line">                <span class="keyword">double</span> progress = _fileData.length/_wholeFileLength;</span><br><span class="line">                progress = progress &gt;= <span class="number">1</span> ? <span class="number">1</span> : progress;</span><br><span class="line">                <span class="keyword">if</span> (progress == <span class="number">1</span>) &#123;</span><br><span class="line">                    <span class="built_in">NSLog</span>(<span class="string">@"分段下载完成"</span>);</span><br><span class="line">                    <span class="built_in">NSLog</span>(<span class="string">@"downloadProgress:%f"</span>, progress);</span><br><span class="line">                    </span><br><span class="line">                    [_operationQueue cancelAllOperations];</span><br><span class="line">                    _operationQueue = <span class="literal">nil</span>;</span><br><span class="line">                    </span><br><span class="line">                    <span class="keyword">if</span> ([<span class="keyword">self</span>.delegate respondsToSelector:<span class="keyword">@selector</span>(multiDownloadDidFinished:)] &amp;&amp; [<span class="keyword">self</span>.delegate respondsToSelector:<span class="keyword">@selector</span>(multiDownloadProgress:)]) &#123;</span><br><span class="line">                        <span class="built_in">NSOperationQueue</span> *mainQueue = [<span class="built_in">NSOperationQueue</span> mainQueue];</span><br><span class="line">                        [mainQueue addOperationWithBlock:^&#123;</span><br><span class="line">                            [<span class="keyword">self</span>.delegate multiDownloadProgress:progress];</span><br><span class="line">                            [<span class="keyword">self</span>.delegate multiDownloadDidFinished:_filePath];</span><br><span class="line"></span><br><span class="line">                        &#125;];</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                    <span class="keyword">if</span> ([<span class="keyword">self</span>.delegate respondsToSelector:<span class="keyword">@selector</span>(multiDownloadProgress:)]) &#123;</span><br><span class="line">                        <span class="built_in">NSOperationQueue</span> *mainQueue = [<span class="built_in">NSOperationQueue</span> mainQueue];</span><br><span class="line">                        [mainQueue addOperationWithBlock:^&#123;</span><br><span class="line">                            [<span class="keyword">self</span>.delegate multiDownloadProgress:progress];</span><br><span class="line">                        &#125;];</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><a href="https://github.com/llMrRongll/TestDownLoad" target="_blank" rel="noopener">Demo下载地址</a></p>
<blockquote>
<p>参考文章<br><a href="http://www.cnblogs.com/wendingding/p/3947550.html" target="_blank" rel="noopener">iOS开发网络篇—多线程断点下载</a></p>
</blockquote>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/roee/tags/ios开发/" rel="tag"># ios开发</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/roee/2017/06/11/Markdown学习/" rel="next" title="MarkDown语法">
                <i class="fa fa-chevron-left"></i> MarkDown语法
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/roee/2017/09/13/工作两年之-感悟-md/" rel="prev" title="工作两年之---感悟.md">
                工作两年之---感悟.md <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel sidebar-panel-active">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/roee/images/avatar.jpg"
               alt="Roee" />
          <p class="site-author-name" itemprop="name">Roee</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/roee/archives/">
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/roee/tags/index.html">
                <span class="site-state-item-count">8</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/llMrRongll" target="_blank" title="github">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                    
                      github
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Roee</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Gemini
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/roee/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/roee/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/roee/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/roee/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/roee/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/roee/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/roee/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/roee/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/roee/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/roee/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/roee/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/roee/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/roee/js/src/bootstrap.js?v=5.1.2"></script>



  


  

    
      <script id="dsq-count-scr" src="https://roee-1.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://rjll.gitee.io/roee/2017/07/08/使用NSURLSession实现iOS大文件分块下载/';
          this.page.identifier = '2017/07/08/使用NSURLSession实现iOS大文件分块下载/';
          this.page.title = '使用NSURLSession实现iOS大文件分块下载';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://roee-1.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  








  





  

  

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
